import { execSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import { Client } from 'ssh2';

// 构建项目
try {
  console.log('开始构建项目...');
  execSync('npm run docs:build', { stdio: 'inherit' });
  console.log('项目构建完成!');
} catch (error) {
  console.error('构建过程中发生错误:', error.message);
  process.exit(1);
}

// 设置变量
const BUILD_DIR = path.join('docs', '.vuepress', 'dist');
import dotenv from 'dotenv';
dotenv.config();
const SERVER_USER = process.env.SERVER_USER;
const SERVER_IP = process.env.SERVER_IP;
const SERVER_PATH = process.env.SERVER_PATH;
const SERVER_PASSWORD = process.env.SERVER_PASSWORD;

// 同步文件到服务器
async function main() {
try {
  console.log('开始同步文件到服务器...');
  
  // 使用ssh2库进行SFTP文件传输
  const conn = new Client();
  
  await new Promise((resolve, reject) => {
    conn.on('ready', () => {
      console.log('SSH连接已建立');
      conn.sftp((err, sftp) => {
        if (err) {
          conn.end();
          return reject(err);
        }
        
        // 递归上传目录
        uploadDir(sftp, BUILD_DIR, SERVER_PATH, (err) => {
          conn.end();
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }).on('error', (err) => {
      reject(err);
    }).connect({
      host: SERVER_IP,
      port: 22,
      username: SERVER_USER,
      password: SERVER_PASSWORD
    });
  });
  
  console.log('文件同步完成!');
} catch (error) {
  console.error('同步过程中发生错误:', error.message);
  process.exit(1);
}

// 递归上传目录的函数
function uploadDir(sftp, localDir, remoteDir, callback) {
  fs.readdir(localDir, (err, files) => {
    if (err) return callback(err);
    
    let pending = files.length;
    if (pending === 0) return callback(null);
    
    const check = (err) => {
      if (err) return callback(err);
      pending--;
      if (pending === 0) callback(null);
    };
    
    sftp.mkdir(remoteDir, () => { // 忽略错误，因为目录可能已存在
      files.forEach((file) => {
        const localPath = path.join(localDir, file);
        const remotePath = path.join(remoteDir, file).replace(/\\/g, '/');
        
        fs.stat(localPath, (err, stats) => {
          if (err) return check(err);
          
          if (stats.isDirectory()) {
            uploadDir(sftp, localPath, remotePath, check);
          } else {
            sftp.fastPut(localPath, remotePath, check);
          }
        });
      });
    });
  });
}

console.log('部署完成!');
console.log('请确保已正确配置服务器密码。');
console.log('详细配置说明请查看 docs/deploy-to-server.md');
}

main().catch(console.error);
